package net.xdclass.service.impl;

import lombok.extern.slf4j.Slf4j;
import net.xdclass.constant.CacheKey;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.enums.SendCodeEnum;
import net.xdclass.component.MailService;
import net.xdclass.service.NotifyService;
import net.xdclass.util.CheckUtil;
import net.xdclass.util.CommonUtil;
import net.xdclass.util.JsonData;
import org.apache.commons.lang3.StringUtils;
import org.mockito.internal.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author guangyang
 * @since 2023-01-18
 **/
@Service
@Slf4j
public class NotifyServiceImpl implements NotifyService {

    @Autowired
    private MailService mailService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 邮件标题
     */
    private static final String SUBJECT="橘光商场验证码";
    /**
     * 邮件内容
     */
    private static final String CONTENT="您好，%s是您绑定帐号的验证码，有效期5分钟，为了您的帐号安全，请勿泄露给他人。（若非本人操作，请忽略本邮件）\n" +
            "橘光账号";
    /**
     * 设置验证码5分钟有效
     */
    private static final int CODE_EXPIRED = 60 * 1000 * 5;


    /**
     *判断是否重复发送
     * 存储验证码到缓存
     * 发送邮箱验证码
     * 存储发送记录
     *
     * @param sendCodeEnum 验证码收件人格式
     * @param to 验证码收件人地址
     * @return Json对象
     */
    @Override
    public JsonData sendCode(SendCodeEnum sendCodeEnum, String to) {

        String cacheKey=String.format(CacheKey.CHECK_CODE_KEY,sendCodeEnum.name(),to);
        String cacheValue = redisTemplate.opsForValue().get(cacheKey);
        if (StringUtils.isNotBlank(cacheValue)){
            long ttl=Long.parseLong(cacheValue.split("_")[1]);
            if (CommonUtil.getCurrentTimestamp()-ttl<CODE_EXPIRED) {
                log.info("重复发送验证码,{}秒之后可重新发送",(CommonUtil.getCurrentTimestamp()-ttl)/1000);
                return JsonData.buildResult(BizCodeEnum.CODE_LIMITED);
            }


        }
            //生成邮箱验证码
            String randomCode = CommonUtil.getRandomCode(4);
            String value=randomCode+"_"+CommonUtil.getCurrentTimestamp();
            redisTemplate.opsForValue().set(cacheKey,value, CODE_EXPIRED,TimeUnit.MILLISECONDS);


        if (CheckUtil.isEmail(to)){
            mailService.sendMail(to,SUBJECT,String.format(CONTENT,randomCode));
            return JsonData.buildSuccess("发送成功");
        } else if (CheckUtil.isPhone(to)) {

        }

        return JsonData.buildResult(BizCodeEnum.CODE_TO_ERROR  );
    }

    /**
     * 校验验证码
     * @param sendCodeEnum
     * @param to
     * @param code 验证码
     * @return
     */
    @Override
    public boolean checkCode(SendCodeEnum sendCodeEnum, String to, String code) {
        String cacheKey=String.format(CacheKey.CHECK_CODE_KEY,sendCodeEnum.name(),to);
        String cacheValue = redisTemplate.opsForValue().get(cacheKey);
        if (StringUtils.isNotBlank(cacheValue)){
            String cacheCode = cacheValue.split("_")[0];
                if (cacheCode.equals(code)){
                    return true;
                }
        }
        return false;
    }
}
